
import 'package:flutter/material.dart';


class PkgRating extends StatefulWidget {
  final double rating;
  final double maxRating;
  final int count;
  final double size;
  final Color unselectedColor;
  final Color selectedColor;
  final Widget unselectedImage;
  final Widget selectedImage;

  PkgRating({
    required this.rating,
    this.maxRating = 5,
    this.count = 5,
    this.size = 30,
    this.unselectedColor = const Color(0xffbbbbbb),
    this.selectedColor = const Color(0xffbbb000),
    Widget? unselectedImage,
    Widget? selectedImage,
  }): unselectedImage = unselectedImage ?? Icon(Icons.star_border, color: unselectedColor, size: size,),
        selectedImage = selectedImage ?? Icon(Icons.star, color: selectedColor, size: size,);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<PkgRating> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Row(
          children: buidUnselectStar(),
        ),
        Row(children: buildSelectStar()),
      ],
    );
  }

  List<Widget> buidUnselectStar() {
    return List.generate(widget.count, (index) {
      return widget.unselectedImage;
    });
  }

  List<Widget> buildSelectStar() {
    //创建stars
    List<Widget> stars = [];

    final star = widget.selectedImage;

    //2.构建满填充的star
    double oneValue = widget.maxRating / widget.count;
    int entireCount = (widget.rating / oneValue).floor();

    stars = List.generate(entireCount, (index) {
      return star;
    });

    //3.构建部分填充的star
    double leftWidth = ((widget.rating / oneValue) - entireCount) * widget.size;
    final helfStar = ClipRect(
      clipper: MyStarClipper(leftWidth: leftWidth),
      child: star,
    );

    stars.add(helfStar);


    if (stars.length > widget.count){
      return stars.sublist(0,widget.count);// 截取 0-widget.count 然后赋值给stars
    }

    return stars;
  }
}

class MyStarClipper extends CustomClipper<Rect> {
  final double leftWidth;

  MyStarClipper({
    required this.leftWidth,
  }) : super();

  @override
  Rect getClip(Size size) {
    return Rect.fromLTRB(0, 0, leftWidth, size.height);
  }

  @override
  bool shouldReclip(covariant MyStarClipper oldClipper) {
    return oldClipper.leftWidth != this.leftWidth;
  }
}
